﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Microsoft.Bing.Application
{
    /// <summary>
    /// Implements a <see cref="System.Windows.Application">Silverlight Application</see> for demonstrating the capabilities of the 
    /// Microsoft Bing search API and the Microsoft Silverlight SDK for Bing.
    /// </summary>
    /// <example>
    /// <para>
    /// The Microsoft Bing SDK is very easy to use in terms of Xaml implementation and binding to the Search data itself. The <see cref="Microsoft.Bing.SearchEnvironment"/> singleton is where
    /// the bulk of the logic and data operations take place. This object is also a <see cref="System.Windows.DependencyObject"/> and implements
    /// <see cref="System.ComponentModel.INotifyPropertyChanged"/>, which provides support for data binding. 
    /// </para>
    /// <para>
    /// To execute a search, you only need to create a <see cref="Microsoft.Bing.Service.SearchRequest"/>, populate its Query property, and
    /// then insure that you have set the SearchMedia property on the <see cref="Microsoft.Bing.SearchEnvironment"/>. Then, call the method
    /// <see cref="Microsoft.Bing.SearchEnvironment.BeginSearch"/>, insuring that you have provided a handler for <see cref="Microsoft.Bing.SearchEnvironment.SearchCompleted"/>.
    /// </para>
    /// <para>
    /// You should also bind any display controls - typically <see cref="System.Windows.Controls.ItemsControl"/> instances, such as ListBox etc - 
    /// to the <see cref="SearchEnvironment.Results"/> property. This property is of type <see cref="Microsoft.Bing.SearchResults"/> and is an observable collection.
    /// This means that you can data bind your <see cref="System.Windows.Controls.ItemsControl"/> instances in advance, like this:
    /// </para>
    /// <code>
    /// //Assumes a ItemsControl named "MyList" exists...
    /// MyList.ItemsSource = SearchEnvironment.Default.Results;
    /// 
    /// //Consume SearchEnvironment Events
    /// SearchEnvironment.Default.SearchStarted += new EventHandler(OnSearchStarted);
    /// SearchEnvironment.Default.SearchCompleted += new EventHandler&lt;SearchResponseEventArgs&gt;(OnSearchCompleted);
    /// SearchEnvironment.Default.Error += new EventHandler&lt;ErrorEventArgs&gt;(OnSearchError);
    /// 
    /// //Begin the Search (Assume a TextBox named "QueryText" exists)
    /// SearchEnvironment.Default.PageSize = 20;
    /// SearchEnvironment.Default.MediaType = SearchMedia.Web;
    /// SearchEnvironment.Default.BeginSearch(QueryText.Text);
    /// </code>
    /// <para>
    /// This should be done prior to executing any searches. Then when a search completes, the <see cref="SearchEnvironment.Results"/> collection will
    /// become populated, if there are avialable results, and your <see cref="System.Windows.Controls.ItemsControl"/> control will automatically data bind
    /// and use the asynchronous layout framework in the Silverlight runtime.
    /// </para>
    /// </example>
    /// <seealso cref="Microsoft.Bing.SearchEnvironment"/>
    /// <seealso cref="System.Windows.Controls.ItemsControl"/>
    public partial class App : System.Windows.Application
    {
        /// <summary>
        /// Instantiates a new <see cref="App"/> instance.
        /// </summary>
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new Page();
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }
        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
